<template>
  <div class="order-payment">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>库存调拨</h1>
      <div class="breadcrumb">仓库管理 > 库存调拨</div>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <div class="search-form">
        <div class="form-item">
          <label>调拨单号</label>
          <input v-model="searchForm.transferCode" type="text" placeholder="请输入调拨单号" />
        </div>
        <div class="form-item">
          <label>调出仓库</label>
          <select v-model="searchForm.fromWarehouseId">
            <option value="">全部</option>
            <option v-for="item in warehouses" :key="item.id" :value="item.id">{{ item.whName }}</option>
          </select>
        </div>
        <div class="form-item">
          <label>调入仓库</label>
          <select v-model="searchForm.toWarehouseId">
            <option value="">全部</option>
            <option v-for="item in warehouses" :key="item.id" :value="item.id">{{ item.whName }}</option>
          </select>
        </div>
        <div class="form-item">
          <label>调拨类型</label>
          <select v-model="searchForm.transferType">
            <option value="">全部</option>
            <option value="内部调拨">内部调拨</option>
            <option value="外部调拨">外部调拨</option>
          </select>
        </div>
        <div class="form-item">
          <label>状态</label>
          <select v-model="searchForm.status">
            <option value="">全部</option>
            <option :value="0">新建</option>
            <option :value="1">待审核</option>
            <option :value="2">已审核</option>
            <option :value="3">已完成</option>
            <option :value="4">已驳回</option>
          </select>
        </div>
        <div class="form-buttons">
          <button class="btn btn-primary" @click="fetchTransferList">查询</button>
          <button class="btn btn-secondary" @click="resetSearch">重置</button>
        </div>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-bar">
      <button class="btn btn-primary" @click="handleCreate">新建调拨单</button>
    </div>

    <!-- 调拨单列表 -->
    <div class="table-container">
      <table class="data-table">
        <thead>
        <tr>
          <th>调拨单号</th>
          <th>调出仓库</th>
          <th>调入仓库</th>
          <th>调拨类型</th>
          <th>调拨日期</th>
          <th>状态</th>
          <th>创建人</th>
          <th>创建时间</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="item in transferList" :key="item.id">
          <td>{{ item.transferCode }}</td>
          <td>{{ getWarehouseName(item.fromWarehouseId) }}</td>
          <td>{{ getWarehouseName(item.toWarehouseId) }}</td>
          <td>{{ item.transferType || '-' }}</td>
          <td>{{ formatDate(item.transferDate) }}</td>
          <td>
            <span :class="getStatusClass(item.status)">{{ getStatusText(item.status) }}</span>
          </td>
          <td>{{ item.createdBy || '-' }}</td>
          <td>{{ formatDate(item.createdAt) }}</td>
          <td>
            <button class="btn btn-small btn-info" @click="handleView(item)">查看</button>
            <button v-if="item.status === 4" class="btn btn-small btn-warning" @click="handleEdit(item)">编辑</button>
            <button v-if="item.status === 0 || item.status === 4" class="btn btn-small btn-success" @click="handleSubmit(item)">提交审核</button>
            <button v-if="item.status === 1" class="btn btn-small btn-primary" @click="handleAudit(item)">审核</button>
            <button v-if="item.status === 2" class="btn btn-small btn-success" @click="handleComplete(item)">完成</button>
            <button v-if="item.status === 0" class="btn btn-small btn-danger" @click="handleDelete(item.id)">删除</button>
          </td>
        </tr>
        <tr v-if="transferList.length === 0">
          <td colspan="9" class="text-center">暂无数据</td>
        </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <div class="pagination-info">
        共{{ pagination.total }}条数据
      </div>
      <div class="pagination-controls">
        <button class="btn btn-small" :disabled="pagination.current <= 1" @click="changePage(pagination.current - 1)">上一页</button>
        <span class="page-info">{{ pagination.current }} / {{ pagination.pages }}</span>
        <button class="btn btn-small" :disabled="pagination.current >= pagination.pages" @click="changePage(pagination.current + 1)">下一页</button>
      </div>
    </div>

    <!-- 查看详情对话框 -->
    <div v-if="detailDialog.visible" class="modal-overlay" @click="detailDialog.visible = false">
      <div class="modal-content" style="width: 80%;" @click.stop>
        <div class="modal-header">
          <h3>调拨单详情 - {{ detailDialog.data.transfer?.transferCode }}</h3>
          <button class="modal-close" @click="detailDialog.visible = false">&times;</button>
        </div>
        <div class="modal-body">
          <div class="detail-section">
            <h4>基本信息</h4>
            <div class="detail-row">
              <div class="detail-item">
                <span class="detail-label">调拨单号：</span>
                <span>{{ detailDialog.data.transfer?.transferCode }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">调出仓库：</span>
                <span>{{ getWarehouseName(detailDialog.data.transfer?.fromWarehouseId) }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">调入仓库：</span>
                <span>{{ getWarehouseName(detailDialog.data.transfer?.toWarehouseId) }}</span>
              </div>
            </div>
            <div class="detail-row">
              <div class="detail-item">
                <span class="detail-label">调拨类型：</span>
                <span>{{ detailDialog.data.transfer?.transferType || '-' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">调拨日期：</span>
                <span>{{ formatDate(detailDialog.data.transfer?.transferDate) }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">状态：</span>
                <span :class="getStatusClass(detailDialog.data.transfer?.status)">
                  {{ getStatusText(detailDialog.data.transfer?.status) }}
                </span>
              </div>
            </div>
            <div class="detail-row">
              <div class="detail-item">
                <span class="detail-label">创建人：</span>
                <span>{{ detailDialog.data.transfer?.createdBy || '-' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">创建时间：</span>
                <span>{{ formatDate(detailDialog.data.transfer?.createdAt) }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">备注：</span>
                <span>{{ detailDialog.data.transfer?.remark || '-' }}</span>
              </div>
            </div>
          </div>
          
          <div class="detail-section">
            <h4>调拨商品明细</h4>
            <table class="data-table">
              <thead>
                <tr>
                  <th>商品名称</th>
                  <th>调拨数量</th>
                  <th>单价</th>
                  <th>总金额</th>
                  <th>批次号</th>
                  <th>有效期</th>
                  <th>备注</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="item in detailDialog.data.items" :key="item.id">
                  <td>{{ getProductName(item.skuId) }}</td>
                  <td>{{ item.qty }}</td>
                  <td>¥{{ item.unitPrice }}</td>
                  <td>¥{{ item.totalAmount }}</td>
                  <td>{{ item.batchNo || '-' }}</td>
                  <td>{{ formatDate(item.expiryDate) }}</td>
                  <td>{{ item.remark || '-' }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="detailDialog.visible = false">关闭</button>
        </div>
      </div>
    </div>

    <!-- 审核对话框 -->
    <div v-if="auditDialog.visible" class="modal-overlay" @click="auditDialog.visible = false">
      <div class="modal-content" style="width: 80%;" @click.stop>
        <div class="modal-header">
          <h3>调拨单审核 - {{ auditDialog.data.transfer?.transferCode }}</h3>
          <button class="modal-close" @click="auditDialog.visible = false">&times;</button>
        </div>
        <div class="modal-body">
          <div class="detail-section">
            <h4>基本信息</h4>
            <div class="detail-row">
              <div class="detail-item">
                <span class="detail-label">调拨单号：</span>
                <span>{{ auditDialog.data.transfer?.transferCode }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">调出仓库：</span>
                <span>{{ getWarehouseName(auditDialog.data.transfer?.fromWarehouseId) }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">调入仓库：</span>
                <span>{{ getWarehouseName(auditDialog.data.transfer?.toWarehouseId) }}</span>
              </div>
            </div>
            <div class="detail-row">
              <div class="detail-item">
                <span class="detail-label">调拨类型：</span>
                <span>{{ auditDialog.data.transfer?.transferType || '-' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">调拨日期：</span>
                <span>{{ formatDate(auditDialog.data.transfer?.transferDate) }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">创建人：</span>
                <span>{{ auditDialog.data.transfer?.createdBy || '-' }}</span>
              </div>
            </div>
          </div>
          
          <div class="detail-section">
            <h4>调拨商品明细</h4>
            <table class="data-table">
              <thead>
                <tr>
                  <th>商品名称</th>
                  <th>调拨数量</th>
                  <th>单价</th>
                  <th>总金额</th>
                  <th>批次号</th>
                  <th>有效期</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="item in auditDialog.data.items" :key="item.id">
                  <td>{{ getProductName(item.skuId) }}</td>
                  <td>{{ item.qty }}</td>
                  <td>¥{{ item.unitPrice }}</td>
                  <td>¥{{ item.totalAmount }}</td>
                  <td>{{ item.batchNo || '-' }}</td>
                  <td>{{ formatDate(item.expiryDate) }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="auditDialog.visible = false">取消</button>
          <button class="btn btn-danger" @click="handleAuditReject" :disabled="auditDialog.loading">驳回</button>
          <button class="btn btn-success" @click="handleAuditApprove" :disabled="auditDialog.loading">通过</button>
        </div>
      </div>
    </div>

    <!-- 新建/编辑对话框 -->
    <div v-if="formDialog.visible" class="modal-overlay" @click="formDialog.visible = false">
      <div class="modal-content" style="width: 90%;" @click.stop>
        <div class="modal-header">
          <h3>{{ formDialog.isEdit ? '编辑调拨单' : '新建调拨单' }}</h3>
          <button class="modal-close" @click="formDialog.visible = false">&times;</button>
        </div>
        <div class="modal-body">
          <div class="form-section">
            <h4>基本信息</h4>
            <div class="form-row">
              <div class="form-item">
                <label>调拨单号</label>
                <input type="text" v-model="formDialog.form.transferCode" :readonly="formDialog.isEdit" />
              </div>
              <div class="form-item">
                <label>调出仓库 <span class="required">*</span></label>
                <select v-model="formDialog.form.fromWarehouseId">
                  <option value="">请选择调出仓库</option>
                  <option v-for="item in warehouses" :key="item.id" :value="item.id">{{ item.whName }}</option>
                </select>
              </div>
              <div class="form-item">
                <label>调入仓库 <span class="required">*</span></label>
                <select v-model="formDialog.form.toWarehouseId">
                  <option value="">请选择调入仓库</option>
                  <option v-for="item in warehouses" :key="item.id" :value="item.id">{{ item.whName }}</option>
                </select>
              </div>
            </div>
            <div class="form-row">
              <div class="form-item">
                <label>调拨类型</label>
                <select v-model="formDialog.form.transferType">
                  <option value="">请选择调拨类型</option>
                  <option value="内部调拨">内部调拨</option>
                  <option value="外部调拨">外部调拨</option>
                </select>
              </div>
              <div class="form-item">
                <label>调拨日期</label>
                <input type="date" v-model="formDialog.form.transferDate" />
              </div>
              <div class="form-item">
                <label>创建人</label>
                <input type="text" v-model="formDialog.form.createdBy" placeholder="请输入创建人" />
              </div>
            </div>
            <div class="form-row">
              <div class="form-item full-width">
                <label>备注</label>
                <textarea v-model="formDialog.form.remark" placeholder="请输入备注"></textarea>
              </div>
            </div>
          </div>

          <div class="form-section">
            <h4>调拨商品明细</h4>
            <div class="table-actions">
              <button class="btn btn-primary btn-small" @click="addItemRow">添加商品</button>
            </div>
            <table class="data-table">
              <thead>
                <tr>
                  <th>商品名称</th>
                  <th>调拨数量</th>
                  <th>单价</th>
                  <th>总金额</th>
                  <th>批次号</th>
                  <th>有效期</th>
                  <th>备注</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in formDialog.form.items" :key="index">
                  <td>
                    <select v-model="item.skuId" @change="() => handleProductSelect(item.skuId, index)">
                      <option value="">请选择商品</option>
                      <option v-for="prod in products" :key="prod.id" :value="prod.id">{{ prod.productName }}</option>
                    </select>
                  </td>
                  <td>
                    <input type="number" v-model.number="item.qty" @input="calculateTotal(index)" min="0" step="0.01" />
                  </td>
                  <td>
                    <input type="number" v-model.number="item.unitPrice" @input="calculateTotal(index)" min="0" step="0.01" />
                  </td>
                  <td>¥{{ item.totalAmount || 0 }}</td>
                  <td>
                    <input type="text" v-model="item.batchNo" placeholder="批次号" />
                  </td>
                  <td>
                    <input type="date" v-model="item.expiryDate" />
                  </td>
                  <td>
                    <input type="text" v-model="item.remark" placeholder="备注" />
                  </td>
                  <td>
                    <button class="btn btn-small btn-danger" @click="removeItemRow(index)" :disabled="formDialog.form.items.length <= 1">删除</button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="formDialog.visible = false">取消</button>
          <button class="btn btn-primary" @click="submitForm" :disabled="formDialog.loading">
            {{ formDialog.loading ? '保存中...' : '保存' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { apiGet, apiPost, apiPut, apiDelete } from '../../utils/api.js'

// 响应式数据
const transferList = ref([])
const warehouses = ref([])
const products = ref([])
const modifiedItems = ref(new Set())

// 搜索表单
const searchForm = reactive({
  transferCode: '',
  fromWarehouseId: '',
  toWarehouseId: '',
  transferType: '',
  status: ''
})

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0,
  pages: 0
})

// 详情对话框
const detailDialog = reactive({
  visible: false,
  data: {}
})

// 审核对话框
const auditDialog = reactive({
  visible: false,
  loading: false,
  data: {}
})

// 表单对话框
const formDialog = reactive({
  visible: false,
  loading: false,
  isEdit: false,
  currentId: null, // 添加当前编辑的调拨单ID
  form: {
    transferCode: '',
    fromWarehouseId: '',
    toWarehouseId: '',
    transferType: '',
    transferDate: '',
    createdBy: '',
    remark: '',
    items: [{ skuId: '', qty: 0, unitPrice: 0, totalAmount: 0, batchNo: '', expiryDate: '', remark: '' }]
  }
})

// 页面加载时获取数据
onMounted(() => {
  fetchTransferList()
  fetchWarehouses()
  fetchProducts()
})

// 获取调拨单列表
const fetchTransferList = async () => {
  try {
    const params = new URLSearchParams({
      page: pagination.current,
      size: pagination.size
    })
    
    if (searchForm.transferCode) params.append('transferCode', searchForm.transferCode)
    if (searchForm.fromWarehouseId) params.append('fromWarehouseId', searchForm.fromWarehouseId)
    if (searchForm.toWarehouseId) params.append('toWarehouseId', searchForm.toWarehouseId)
    if (searchForm.transferType) params.append('transferType', searchForm.transferType)
    if (searchForm.status !== '') params.append('status', searchForm.status)
    
    const result = await apiGet(`/ware-service/ware/transfer?${params}`)
    if (result && result.data && result.data.records) {
      transferList.value = result.data.records || []
      pagination.total = result.data.total || 0
      pagination.pages = result.data.pages || 0
    } else {
      transferList.value = []
      pagination.total = 0
      pagination.pages = 0
    }
  } catch (error) {
    console.error('获取调拨单列表失败:', error)
    transferList.value = []
    pagination.total = 0
    pagination.pages = 0
  }
}

// 获取仓库列表
const fetchWarehouses = async () => {
  try {
    const params = new URLSearchParams({
      page: 1,
      size: 100
    })
    const result = await apiGet(`/ware-service/warehouse/list?${params}`)
    if (result && result.records) {
      warehouses.value = result.records || []
    } else if (result && result.data && result.data.records) {
      warehouses.value = result.data.records || []
    } else {
      warehouses.value = []
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    warehouses.value = []
  }
}

// 获取商品列表
const fetchProducts = async () => {
  try {
    const params = new URLSearchParams({
      page: 1,
      size: 100
    })
    const result = await apiGet(`/ware-service/ware/sku/list?${params}`)
    if (result && result.records) {
      products.value = result.records || []
    } else if (result && result.data && result.data.records) {
      products.value = result.data.records || []
    } else {
      products.value = []
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    products.value = []
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.transferCode = ''
  searchForm.fromWarehouseId = ''
  searchForm.toWarehouseId = ''
  searchForm.transferType = ''
  searchForm.status = ''
  pagination.current = 1
  fetchTransferList()
}

// 分页切换
const changePage = (page) => {
  pagination.current = page
  fetchTransferList()
}

// 获取仓库名称
const getWarehouseName = (id) => {
  if (!id) return '-'
  const warehouse = warehouses.value.find(w => w.id === id)
  return warehouse ? warehouse.whName : '-'
}

// 获取商品名称
const getProductName = (skuId) => {
  if (!skuId) return '-'
  const product = products.value.find(p => p.id === skuId)
  return product ? product.productName : '-'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '新建',
    1: '待审核',
    2: '已审核',
    3: '已完成',
    4: '已驳回'
  }
  return statusMap[status] || '未知'
}

// 获取状态类名
const getStatusClass = (status) => {
  const classMap = {
    0: 'status-info',
    1: 'status-warning',
    2: 'status-success',
    3: 'status-success',
    4: 'status-danger'
  }
  return `status ${classMap[status] || ''}`
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

// 查看详情
const handleView = async (item) => {
  try {
    const result = await apiGet(`/ware-service/ware/transfer/${item.id}`)
    if (result && result.data) {
      detailDialog.data = result.data || {}
    } else {
      detailDialog.data = {}
    }
    detailDialog.visible = true
  } catch (error) {
    console.error('获取调拨单详情失败:', error)
    detailDialog.data = {}
  }
}

// 新建调拨单
const handleCreate = () => {
  formDialog.isEdit = false
  formDialog.currentId = null // 重置当前编辑ID
  formDialog.form = {
    transferCode: `TF${new Date().getTime()}`,
    fromWarehouseId: '',
    toWarehouseId: '',
    transferType: '',
    transferDate: new Date().toISOString().split('T')[0],
    createdBy: '当前用户',
    remark: '',
    items: [{ skuId: '', qty: 0, unitPrice: 0, totalAmount: 0, batchNo: '', expiryDate: '', remark: '' }]
  }
  formDialog.visible = true
}

// 编辑调拨单
const handleEdit = async (item) => {
  try {
    const result = await apiGet(`/ware-service/ware/transfer/${item.id}`)
    formDialog.isEdit = true
    formDialog.currentId = item.id // 设置当前编辑的调拨单ID
    if (result && result.data) {
      const data = result.data
      formDialog.form = {
        transferCode: data.transfer?.transferCode || '',
        fromWarehouseId: data.transfer?.fromWarehouseId || '',
        toWarehouseId: data.transfer?.toWarehouseId || '',
        transferType: data.transfer?.transferType || '',
        transferDate: data.transfer?.transferDate ? new Date(data.transfer.transferDate).toISOString().split('T')[0] : '',
        createdBy: data.transfer?.createdBy || '',
        remark: data.transfer?.remark || '',
        items: data.items?.map(item => ({
          skuId: item.skuId || '',
          qty: item.qty || 0,
          unitPrice: item.unitPrice || 0,
          totalAmount: item.totalAmount || 0,
          batchNo: item.batchNo || '',
          expiryDate: item.expiryDate ? new Date(item.expiryDate).toISOString().split('T')[0] : '',
          remark: item.remark || ''
        })) || [{ skuId: '', qty: 0, unitPrice: 0, totalAmount: 0, batchNo: '', expiryDate: '', remark: '' }]
      }
    } else {
      formDialog.form = {
        transferCode: '',
        fromWarehouseId: '',
        toWarehouseId: '',
        transferType: '',
        transferDate: '',
        createdBy: '',
        remark: '',
        items: [{ skuId: '', qty: 0, unitPrice: 0, totalAmount: 0, batchNo: '', expiryDate: '', remark: '' }]
      }
    }
    formDialog.visible = true
  } catch (error) {
    console.error('获取调拨单详情失败:', error)
  }
}

// 提交审核
const handleSubmit = async (item) => {
  if (item.status === 4 && !modifiedItems.value.has(item.id)) {
    alert('已驳回的调拨单必须先进行修改才能提交审核\n请先点击"编辑"按钮修改调拨单内容')
    return
  }
  
  if (confirm(`确定要提交调拨单 ${item.transferCode} 进行审核吗？`)) {
    try {
      const result = await apiPost(`/ware-service/ware/transfer/${item.id}/submit`)
      if (result && (result.code === 0 || result.status === 200 || result.success)) {
        alert('提交审核成功')
        modifiedItems.value.delete(item.id)
        await fetchTransferList()
      } else {
        alert('提交审核失败')
      }
    } catch (error) {
      console.error('提交审核失败:', error)
      alert('提交审核失败')
    }
  }
}

// 审核
const handleAudit = async (item) => {
  try {
    const result = await apiGet(`/ware-service/ware/transfer/${item.id}`)
    if (result && result.data) {
      auditDialog.data = result.data || {}
    } else {
      auditDialog.data = {}
    }
    auditDialog.visible = true
  } catch (error) {
    console.error('获取调拨单详情失败:', error)
    auditDialog.data = {}
  }
}

// 审核通过
const handleAuditApprove = async () => {
  auditDialog.loading = true
  try {
    const result = await apiPost(`/ware-service/ware/transfer/${auditDialog.data.transfer.id}/approve`)
    if (result && (result.code === 0 || result.status === 200 || result.success)) {
      alert('审核通过成功')
      auditDialog.visible = false
      await fetchTransferList()
    } else {
      alert('审核通过失败')
    }
  } catch (error) {
    console.error('审核通过失败:', error)
    alert('审核通过失败')
  } finally {
    auditDialog.loading = false
  }
}

// 审核驳回
const handleAuditReject = async () => {
  auditDialog.loading = true
  try {
    const result = await apiPost(`/ware-service/ware/transfer/${auditDialog.data.transfer.id}/reject`)
    if (result && (result.code === 0 || result.status === 200 || result.success)) {
      alert('审核驳回成功')
      auditDialog.visible = false
      await fetchTransferList()
    } else {
      alert('审核驳回失败')
    }
  } catch (error) {
    console.error('审核驳回失败:', error)
    alert('审核驳回失败')
  } finally {
    auditDialog.loading = false
  }
}

// 完成调拨
const handleComplete = async (item) => {
  if (confirm(`确定要完成调拨单 ${item.transferCode} 吗？`)) {
    try {
      const result = await apiPost(`/ware-service/ware/transfer/${item.id}/complete`)
      if (result && (result.code === 0 || result.status === 200 || result.success)) {
        alert('调拨完成成功')
        await fetchTransferList()
      } else {
        const errorMsg = result?.message || '调拨完成失败'
        alert(`调拨完成失败: ${errorMsg}`)
      }
    } catch (error) {
      console.error('完成调拨失败:', error)
      
      // 解析错误信息
      let errorMessage = '完成调拨失败'
      if (error.message) {
        if (error.message.includes('调出仓库库存不足')) {
          errorMessage = '调拨完成失败：调出仓库库存不足，请检查库存数量'
        } else if (error.message.includes('调入仓库库存增加失败')) {
          errorMessage = '调拨完成失败：调入仓库库存增加失败'
        } else if (error.message.includes('500')) {
          errorMessage = '调拨完成失败：服务器内部错误，请检查库存数据'
        } else {
          errorMessage = `调拨完成失败：${error.message}`
        }
      }
      
      alert(errorMessage)
    }
  }
}

// 删除调拨单
const handleDelete = async (id) => {
  if (confirm('确定要删除此调拨单吗？')) {
    try {
      const result = await apiDelete(`/ware-service/ware/transfer/${id}`)
      if (result && (result.code === 0 || result.status === 200 || result.status === 204 || result.success)) {
        alert('删除成功')
        await fetchTransferList()
      } else {
        alert('删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      alert('删除失败')
    }
  }
}

// 商品选择处理
const handleProductSelect = async (skuId, index) => {
  if (skuId) {
    try {
      // 这里可以根据需要获取商品的价格信息
      // 暂时设置为0，用户手动输入
      formDialog.form.items[index].unitPrice = 0
      formDialog.form.items[index].totalAmount = 0
    } catch (error) {
      console.error('获取商品信息失败:', error)
    }
  }
}

// 计算总金额
const calculateTotal = (index) => {
  const item = formDialog.form.items[index]
  item.totalAmount = (item.qty || 0) * (item.unitPrice || 0)
}

// 添加商品行
const addItemRow = () => {
  formDialog.form.items.push({ skuId: '', qty: 0, unitPrice: 0, totalAmount: 0, batchNo: '', expiryDate: '', remark: '' })
}

// 删除商品行
const removeItemRow = (index) => {
  if (formDialog.form.items.length > 1) {
    formDialog.form.items.splice(index, 1)
  }
}

// 提交表单
const submitForm = async () => {
  if (!formDialog.form.fromWarehouseId) {
    alert('请选择调出仓库')
    return
  }
  
  if (!formDialog.form.toWarehouseId) {
    alert('请选择调入仓库')
    return
  }
  
  if (formDialog.form.fromWarehouseId === formDialog.form.toWarehouseId) {
    alert('调出仓库和调入仓库不能相同')
    return
  }
  
  if (!formDialog.form.items.some(item => item.skuId)) {
    alert('请至少添加一个商品')
    return
  }
  
  formDialog.loading = true
  
  try {
    const data = {
      ...formDialog.form,
      transferDate: formDialog.form.transferDate ? formDialog.form.transferDate : null,
      items: formDialog.form.items.filter(item => item.skuId).map(item => ({
        ...item,
        expiryDate: item.expiryDate ? item.expiryDate : null
      }))
    }
    
    let result
    if (formDialog.isEdit) {
      result = await apiPut(`/ware-service/ware/transfer/${formDialog.currentId}`, data)
      // 标记该单据为已修改
      modifiedItems.value.add(formDialog.currentId)
    } else {
      result = await apiPost('/ware-service/ware/transfer', data)
    }
    
    if (result && (result.code === 0 || result.status === 200 || result.status === 201 || result.success)) {
      alert(formDialog.isEdit ? '修改成功' : '创建成功')
      formDialog.visible = false
      await fetchTransferList()
    } else {
      alert('提交失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    alert('提交失败')
  } finally {
    formDialog.loading = false
  }
}
</script>

<style scoped>
.order-payment {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0 0 5px 0;
  color: #333;
  font-size: 24px;
}

.breadcrumb {
  color: #666;
  font-size: 14px;
}

.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.search-form {
  display: flex;
  gap: 20px;
  align-items: end;
  flex-wrap: wrap;
}

.form-item {
  display: flex;
  flex-direction: column;
  min-width: 150px;
}

.form-item label {
  margin-bottom: 5px;
  font-weight: 500;
  color: #333;
}

.form-item input,
.form-item select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-buttons {
  display: flex;
  gap: 10px;
}

.action-bar {
  margin-bottom: 20px;
}

.table-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.data-table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #333;
}

.data-table tr:hover {
  background-color: #f8f9fa;
}

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 0 20px;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.page-info {
  font-size: 14px;
  color: #666;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.modal-close {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
}

.modal-body {
  padding: 20px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 20px;
  border-top: 1px solid #eee;
}

.detail-section {
  margin-bottom: 30px;
}

.detail-section h4 {
  margin: 0 0 15px 0;
  color: #333;
  border-bottom: 2px solid #007bff;
  padding-bottom: 5px;
}

.detail-row {
  display: flex;
  gap: 30px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.detail-item {
  display: flex;
  align-items: center;
  min-width: 200px;
}

.detail-label {
  font-weight: 500;
  color: #666;
  margin-right: 10px;
  min-width: 80px;
}

.form-section {
  margin-bottom: 30px;
}

.form-section h4 {
  margin: 0 0 15px 0;
  color: #333;
  border-bottom: 2px solid #007bff;
  padding-bottom: 5px;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.form-row .form-item {
  flex: 1;
  min-width: 200px;
}

.form-row .form-item.full-width {
  flex: 100%;
}

.form-item textarea {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  min-height: 80px;
  resize: vertical;
}

.required {
  color: red;
}

.table-actions {
  margin-bottom: 15px;
}

.status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-info {
  background-color: #e3f2fd;
  color: #1976d2;
}

.status-warning {
  background-color: #fff3e0;
  color: #f57c00;
}

.status-success {
  background-color: #e8f5e8;
  color: #2e7d32;
}

.status-danger {
  background-color: #ffebee;
  color: #c62828;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  gap: 5px;
  transition: all 0.2s;
}

.btn-primary {
  background-color: #007bff;
  color: white;
}

.btn-primary:hover {
  background-color: #0056b3;
}

.btn-secondary {
  background-color: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background-color: #545b62;
}

.btn-success {
  background-color: #28a745;
  color: white;
}

.btn-success:hover {
  background-color: #1e7e34;
}

.btn-warning {
  background-color: #ffc107;
  color: #212529;
}

.btn-warning:hover {
  background-color: #e0a800;
}

.btn-danger {
  background-color: #dc3545;
  color: white;
}

.btn-danger:hover {
  background-color: #c82333;
}

.btn-info {
  background-color: #17a2b8;
  color: white;
}

.btn-info:hover {
  background-color: #138496;
}

.btn-small {
  padding: 4px 8px;
  font-size: 12px;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.text-center {
  text-align: center;
}
</style>
